
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "BSP.h"
#include "Util.h"
#include "logging/Log.h"
#include "Env.h"
#include "Des.h"
#include "ReaderBLE.h"

static uint8_t bleRxBuffer[300];
static uint16_t bleRxLength;
static int bleRxTime;
static int bleLife;
uint8_t bleLen;
uint8_t bleData[128];

static void BLE_RxCallback(uint8_t rx){
	if(bleRxLength < (sizeof(bleRxBuffer)-1)){
		bleRxBuffer[bleRxLength++] = rx;
		bleRxTime = 5;
	}
}

void Reader_BLE_RxTick(void){
	if(bleLife){
		bleLife--;
		if(bleLife == 0){
			bleRxLength = 0;
		}
	}
	
	if(bleRxTime > 0){
		bleRxTime--;
		if(bleRxTime == 0){
			bleLife = 1000;
		}
	}
	
}

void Reader_BLE_Init(void){
	bleRxLength = 0;
	bleRxTime = -1;
	BSP_Uart_SetRxCallback(0, BLE_RxCallback);
}

int Reader_BLE_Read(uint8_t *sn, uint8_t* nlen){
	if(bleRxTime == 0){
		bleRxTime = -1;
		if(bleRxLength != 8){
			return BLE_ERR_LEN;
		}
		LOG_BUF(0, RTT_CTRL_TEXT_BRIGHT_WHITE, "ble cypt", bleRxBuffer, bleRxLength);
		unsigned int plaintext_len = 0;
		unsigned char key[16] = "1234567890ABCDEF";
		des_decrypt_data(bleRxBuffer, 8, sn, &plaintext_len, key, 16);
		*nlen = 8;
		LOG_BUF(0, RTT_CTRL_TEXT_BRIGHT_WHITE, "ble plain", sn, *nlen);
		return BLE_ERR_OK;
	}
	
	return BLE_ERR_NONE;
}




